﻿using Avalonia.Controls.Presenters;
using Avalonia.VisualTree;

namespace KinonekoSoftware.Studio.Resources.Controls
{

    /// <summary>
    /// Zoom content presenter control.
    /// </summary>
    internal sealed class ZoomContentPresenter : ContentPresenter
    {
        public event ContentSizeChangedHandler ContentSizeChanged;

        private Size _contentSize;

        public Size ContentSize
        {
            get => _contentSize;
            private set
            {
                if (_contentSize == value)
                    return;

                _contentSize = value;
                ContentSizeChanged?.Invoke(this, _contentSize);
            }
        }

        private const int InfiniteSize = 1000000000;

        /// <inheritdoc />
        protected override Size MeasureOverride(Size constraint)
        {
            base.MeasureOverride(new Size(double.PositiveInfinity, double.PositiveInfinity));

            return new Size(
                            double.IsInfinity(constraint.Width) ? InfiniteSize : constraint.Width,
                            double.IsInfinity(constraint.Height) ? InfiniteSize : constraint.Height);
        }

        /// <inheritdoc />
        protected override Size ArrangeOverride(Size arrangeSize)
        {
            var uiElement = VisualChildren.Count > 0
                ? this.GetVisualChildren().FirstOrDefault() as Control
                : null;
            if (uiElement is null)
                return arrangeSize;

            ContentSize = uiElement.DesiredSize;
            uiElement.Arrange(new Rect(uiElement.DesiredSize));

            return arrangeSize;
        }
    }
}